<template>
  <div class="login-container">
    <div class="login-box">
      <!-- 头像区域 -->
      <div class="avatar-box">
        <img src="@/assets/logo.png" alt="">
      </div>
      <!-- 表单登录区域 -->
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginFormRules" label-width="0px">
        <!-- 账号 -->
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" prefix-icon="iconfont icon-user"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input type="password" v-model="loginForm.password" prefix-icon="iconfont icon-3702mima"></el-input>
        </el-form-item>
        <!-- 登录和重置按钮 -->
        <el-form-item class="btns-box">
          <el-button type="primary" @click="login">登录</el-button>
          <el-button type="info" @click="resetLoginForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { sendLoginAPI } from '@/api/login.js'
export default {
  data () {
    return {
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      loginFormRules: {
        username: [
          { required: true, message: '请输入登录名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ]
      }
    }
  },

  created () {

  },

  methods: {
    // 点击重置按钮，重置表单数据
    resetLoginForm () {
      // this 获取的是该表单的实例对象
      // console.log(this)
      this.$refs.loginFormRef.resetFields()
    },
    // 点击登录
    login () {
      // 表单的预验证
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await sendLoginAPI(this.loginForm)
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('昵称或密码错误')
        this.$message.success('登录成功')
        // 将token保存到sessionStorage中
        window.sessionStorage.setItem('token', res.data.token)
        // 登录成功，跳转路由
        this.$router.push('/home')
      })
    }
  }
}
</script>

<style scoped lang="less">
.login-container {
  height: 100%;
  background-color: #2b4b6b;

  .login-box {
    width: 450px;
    height: 300px;
    background-color: #fff;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

    .avatar-box {
      width: 130px;
      height: 130px;
      border-radius: 50%;
      position: relative;
      left: 50%;
      transform: translate(-50%, -50%);
      background-color: #fff;
      border: 2px solid #eee;

      img {
        width: 100%;
      }
    }
  }

  .el-form {
    position: relative;
    bottom: 20px;
    padding: 0 20px;

    .btns-box {
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
